/**
 * @description user service
 * @author 高
 */

const { User } = require("../db/model/index");
const { formatUser } = require("./_format");

/**
  * 获取用户信息
  * @param {String} userName 用户名
  * @param {String} password 密码
  */
async function getUserInfo(userName, password) {
  // 查询条件
  const whereOpt = {
    userName
  };

  if (password) {
    // 对象做拼接
    Object.assign(whereOpt, { password });
  }

  // 查询
  const result = await User.findOne({
    attributes: ["id", "userName", "nickName", "picture", "city"],
    where: whereOpt
  });

  if (result == null) {
    // 未找到
    return result;
  }

  // 格式化
  const formatRes = formatUser(result.dataValues);
  return formatRes;
}

/**
  * 创建用户
  * @param {String} userName 用户名
  * @param {String} password 密码
  * @param {number} gender 行呗
  * @param {String} nickName 昵称
  */
async function createUser({ userName, password, gender = 3, nickName }) {
  const result = User.create({
    userName,
    password,
    gender,
    nickName: nickName ? nickName : userName
  });

  return result.dataValues;
}

/**
 * 删除用户
 * @param {string} userName 用户名
 */
async function deleteUser(userName) {
  const result = await User.destroy({
    where: {
      userName
    }
  });
  // result是删除的行数，成功行数大于0
  return result > 0;
}

/**
 * 更新用户信息
 * @param {object} param0 要修改的内容 {newPassword,newNickName,newPicture,newCity}
 * @param {object} param1 查询条件 {userName,password}
 */
async function updateUser({ newPassword, newNickName, newPicture, newCity }, { userName, password }) {
  // 拼接修改内容
  const updateData = {};
  if (newPassword) {
    updateData.password = newPassword;
  }
  if (newNickName) {
    updateData.nickName = newNickName;
  }
  if (newPicture) {
    updateData.picture = newPicture;
  }
  if (newCity) {
    updateData.city = newCity;
  }

  // 拼接查询条件
  const whereData = {
    userName
  };
  if (password) {
    whereData.password = password;
  }

  // 执行修改
  const result = await User.update(updateData, {
    where: whereData
  });

  //  更新行数大于0 更新成功，否则失败
  return result[0] > 0;
}

module.exports = {
  getUserInfo,
  createUser,
  deleteUser,
  updateUser
};